package com.hm.service.impl.auth;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.entity.auth.SessionBean;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.main.SessionService;
import com.hm.service.utils.EncryptionUtils;
import com.hm.service.utils.SoleIdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;

@Service
public class SessionServiceImpl extends BaseServiceImpl implements SessionService {

    private static final Logger logger = LoggerFactory.getLogger(SessionServiceImpl.class);

    //秘钥
    private static final String secretKey = "XMqeJONpR3Dg6KlXPcvV2hRD4QWBuaNb";

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public SessionServiceImpl(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String generateSessionId() {
        //构建sessionID
        long l = System.currentTimeMillis();
        SessionBean sessionBean = new SessionBean();
        sessionBean.issueTime = String.valueOf(l);//发行时间
        sessionBean.sessionIdKey = SoleIdUtils.getUUID();//唯一key
        String jsonString = JSON.toJSONString(sessionBean);
        String sessionId = EncryptionUtils.encrypt(secretKey, jsonString);
        //保存至redis,默认有效期是2天(单位：秒)
        long survivalTime = 60 * 60 * 24 * 2;
        try (Jedis jedis = jedisPool.getResource()) {
            String sessionIdKey = sessionBean.sessionIdKey;
            jedis.setex(sessionIdKey, survivalTime, sessionId);
        }
        return sessionId;
    }

    @Override
    public HashMap<String, String> verifier(String sessionId) {
        HashMap<String, String> resMap = new HashMap<>();
        if (sessionId == null || sessionId.isEmpty()) {
            resMap.put("state", "004");
            resMap.put("msg", "sessionId为空");
            return resMap;
        }
        //解密sessionId
        String sessionIdJson = EncryptionUtils.decrypt(secretKey, sessionId);
        //解析sessionId
        SessionBean sessionBean = JSONObject.parseObject(sessionIdJson, SessionBean.class);
        String sessionIdKey = sessionBean.sessionIdKey;
        if (sessionIdKey == null || sessionIdKey.isEmpty()) {
            resMap.put("state", "001");
            resMap.put("msg", "sessionId解析失败");
            return resMap;
        }
        try (Jedis jedis = jedisPool.getResource()) {
            //通过sessionIdKey拿到redis中的sessionId
            boolean exists = jedis.exists(sessionIdKey);
            if (!exists) {
                //不存在，说明过期了
                resMap.put("state", "002");
                resMap.put("msg", "session已过期");
                return resMap;
            }
            //取出存在redis的sessionID
            String latestSessionId = jedis.get(sessionIdKey);
            if (latestSessionId == null || !latestSessionId.equals(sessionId)) {
                //说明sessionId异常
                resMap.put("state", "003");
                resMap.put("msg", "session异常");
                return resMap;
            }
            resMap.put("state", "000");
            resMap.put("msg", "验证通过");
            return resMap;
        }
    }


}
